package com.zyl.controller;

import com.zyl.pojo.User;
import com.zyl.util.MD5Util;
import com.zyl.util.ResultVoUtil;
import com.zyl.vo.ResultVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: Zyl
 * @Param:
 * @return:
 * @Description:
 */

@Controller
public class UploaderController {

    @PostMapping("/article/articlePicture")//测试的url接口
    @ResponseBody
    public ResultVo imgUpload(@RequestBody MultipartFile file)
            throws IOException {
        String fileUploadPath="src\\main\\resources\\static\\article\\image\\";
        //我这里用的springboot 在application.properties中配置，使用@Value 获取的文件上传目录

        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.indexOf("."));
        String localFileName = MD5Util.md5(file.getInputStream()) + suffix;
        File localFile = new File(fileUploadPath + localFileName);
        if (!localFile.exists()) {
            localFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(
                    localFile);
            try {
                FileInputStream fs = (FileInputStream) file.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = fs.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
                fs.close();
            } catch (NullPointerException e) {
                e.printStackTrace();
            } finally {
                return ResultVoUtil.success("http://localhost:8084/article/image/"+localFileName);
            }
        } else {
            System.out.println("已经有文件了可以直接返回");
        }
        return  ResultVoUtil.success("http://localhost:8084/article/image/"+localFileName);

    }
}
